package com.cold.demo.web.util;

import java.util.*;

/**
 * @author Administrator
 */
public class CollectionUtil {

    private static final List emptyList = new ArrayList();
    private static final Set emptySet = new HashSet();

    public static <E> String join(Collection<E> coll, String sp, String def) {
        if (coll == null || coll.size() == 0) {
            return def;
        }
        StringBuilder buffer = new StringBuilder();
        int i = 0;
        for (E next : coll) {
            if (i == 0) {
                buffer.append(next);
            } else {
                buffer.append(sp).append(next);
            }
            i++;
        }
        return buffer.toString();
    }

    public static <E> String join(Collection<E> coll, String sp) {
        return join(coll, sp, null);
    }

    public static <E> String join(Collection<E> list) {
        return join(list, "、");
    }

    /**
     * 数组转集合
     */
    public static <E> List<E> asList(E... es) {
        if (es == null || es.length == 0) {
            return emptyList;
        }
        List<E> list = new ArrayList<>(es.length);
        Collections.addAll(list, es);
        return list;
    }

    /**
     * 数组转集合
     */
    public static <E> Set<E> asSet(E... es) {
        if (es == null || es.length == 0) {
            return emptySet;
        }
        Set<E> set = new HashSet<>(es.length);
        for (E e : es) {
            set.add(e);
        }
        return set;
    }


    /**
     * 获取列表的第一个元素
     */
    public static <E> E getFirst(List<E> es) {
        return (es == null || es.size() == 0) ? null : es.get(0);
    }


    /**
     * 过滤传值过来的集合，如果为集合长度为0就返回null
     */
    public static <E> List<E> getList(List<E> es) {
        return (es == null || es.size() == 0) ? null : es;
    }

}
